package vacuum.noSpam;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.LinkedList;
import java.util.Scanner;

public class Dictionary
{

	private File location;

	private boolean verbose;

	private String[] dictionary;

	public Dictionary(File location, boolean preload, boolean verbose){
		this.verbose = verbose;
		this.location = location;
		if(!location.exists()){
			NoSpam.download(NoSpam.dictionary, location);
		}
		if(preload)
			try{
				loadDictionary();
			} catch (IOException ex){
				ex.printStackTrace();
			}
	}

	public float checkMatches(String message){
		String[] s = strip(message.toLowerCase()).split(" ");
		int collisions = 0;
		if(dictionary != null){
			strings: for (int i = 0; i < s.length; i++)
			{
				//do binary search, efficiency nlog(n)
				int pos = dictionary.length / 2;
				int delta = dictionary.length / 4;
				while(true){
					int val = dictionary[pos].compareTo(s[i]);
					if(val == 0){
						collisions++;
						continue strings;
					} else{
						if(delta == 0){
							continue strings;
						}
						if (val < 0){
							pos -= delta;
						} else if (val > 0){
							pos += delta;
						}
						delta /= 2;
					}
				}
			}
		} else {
			Scanner read;
			try
			{
				//search efficiency n*n
				read = new Scanner(location);
				while(read.hasNext()){
					String line = read.nextLine();
					for (int i = 0; i < s.length; i++)
					{
						if(s[i].equalsIgnoreCase(line))
							collisions++;
					}
				}
			} catch (FileNotFoundException e)
			{
				e.printStackTrace();
			}
		}
		log(collisions + ", " + s.length);
		return (((float)collisions)/s.length); //percent in dictionary
	}

	private void loadDictionary() throws FileNotFoundException{
		Scanner s = new Scanner(location);
		LinkedList<String> ll = new LinkedList<String>();
		while(s.hasNext()){
			ll.add(s.nextLine().toLowerCase());
			log("Adding " + ll.getLast() + ".");
		}
		dictionary = ll.toArray(new String[ll.size()]);
	}
	
	private void log(String s){
		if(verbose){
			System.out.println("[NoSpam]->[Dictionary]" + s);
		}
	}
	
	private String strip(String s){
		StringBuffer buf = new StringBuffer();
		for(char c : s.toLowerCase().toCharArray()){
			if(c >= 'a' && c <= 'z')
				buf.append(c);
		}
		return buf.toString();
	}
}
